# !/usr/bin/python27
# -*- coding:utf-8 -*-

"""
Auther: chenx
Date: 2018-04-30

"""

import http.client, re, threading
import urllib.parse
from calendar import timegm
from hprose.common import HproseException
import time
from hprose.client import HproseClient
import uuid
import pika #导入RabbitMQ

class HproseRabbitMQClient(HproseClient):
    def __init__(self, connect = None):
        self.__connect = connect
        self.__channel = None
        self.__callback_queue = None
        self.__corr_id = None
        self._response = None
        self.__exchange_name = None
        self.__routing_name = None
        super(HproseRabbitMQClient, self).__init__(None)

    """回调函数，用来接收返回的数据"""
    def callback(self, channel, method, properties, body):
        len = 0
        for byte in body:
            if byte != 0:
                len += 1
            else:
                break
        self._response = body[:len]
        #输出相关调试信息
        print(" [x] Received.    cor_id: %s data: %r" % (self.__corr_id, self._response))
        # if self.__corr_id == properties.correlation_id:
        #     print(" [x] The corr_id_resp is Right. cor_id: %s" %(self.__corr_id))
        # else:
        #     print(" [x] The corr_id_resp is Wrong! cor_id: %s" %(self.__corr_id))
        #返回Ack应答
        channel.basic_ack(delivery_tag = method.delivery_tag)

    def setRabbitMQConnect(self, rabbit_connect, exchange_name='', routing_name=''):
        self.__connect = rabbit_connect

        self.__channel = self.__connect.channel()

        result = self.__channel.queue_declare(exclusive=True)
        self.__callback_queue = result.method.queue

        self.__channel.basic_consume(self.callback, no_ack=False,
                                   queue=self.__callback_queue)
        self.__exchange_name = exchange_name
        self.__routing_name = routing_name

    def _sendAndReceive(self, data):
        self._response = None
        self.__corr_id = str(uuid.uuid4())
        self.__channel.basic_publish(exchange=self.__exchange_name,
                                   routing_key=self.__routing_name,
                                   properties=pika.BasicProperties(
                                       reply_to = self.__callback_queue,
                                       correlation_id = self.__corr_id,
                                   ),
                                   body=data)
        print(" [x] Transferred. cor_id: %s data: %r" % (self.__corr_id, data))
        while self._response is None:
            self.__connect.process_data_events()
        return self._response
        # httpclient.close()
        # raise HproseException('%d:%s' % (resp.status, resp.reason))